/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.cx1.dao.api.IBlogDao;
import org.cx1.dao.api.IPhotoDao;
import org.cx1.dao.impl.BlogDao;
import org.cx1.dao.impl.PhotoDao;
import org.cx1.model.Blog;
import org.cx1.model.Photo;
import org.cx1.model.ds.MockDS;
import org.cx1.model.utils.BlogComparator;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.service.api.IBlogService;
import org.cx1.service.api.IPhotoService;
import org.cx1.service.utils.IDGenerator;

/**
 *
 * @author ECH
 */
public class DBlogService implements IBlogService {

    private IBlogDao blogDao = new BlogDao();
    private IPhotoDao photoDao = new PhotoDao();
    
    private IPhotoService photoService = new DPhotoService();
    
    @Override
    public ServiceResponse<String> create(Blog blog) {
        ServiceResponse<String> response = new ServiceResponse<String>();
        String id = null;        
        try {            
            Blog entry = new Blog();
            id = IDGenerator.generateID();
            
            entry.setBlogTypeID(blog.getBlogTypeID());
            
            entry.setId(id);
            entry.setTitle(blog.getTitle());
            entry.setBody(blog.getBody());
            entry.setShortBody(blog.getShortBody());
            
            entry.setAuthorName(blog.getAuthorName());
            entry.setAuthorGPlus(blog.getAuthorGPlus());
            
            entry.setTagIDs(blog.getTagIDs());
            entry.setPlaceIDs(blog.getPlaceIDs());
            
            entry.setActive(true);
            entry.setDateCreated(new Date());
            entry.setDateModified(new Date());
                        
            blogDao.add(entry);
            
            response.setResponse(id);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse("");
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<Blog> read(String id) {
        ServiceResponse<Blog> response = new ServiceResponse<Blog>();
        Blog blog = null;
        try {            
            blog = blogDao.getById(id);
            buildBlogAttribute(blog);
            
            response.setResponse(blog);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<List<Blog>> readAll(int offset, int limit) {
        ServiceResponse<List<Blog>> response = new ServiceResponse<List<Blog>>();
        List<Blog> blogs = new ArrayList<Blog>();
        try {            
            List<Blog> records = blogDao.getAll();
            if (records != null && records.size() > 0) {
                if (offset == 0 && limit == 0) {
                    blogs.addAll(records);
                }
                else if (offset < records.size() && limit < records.size()) {
                    blogs.addAll( records.subList(offset, limit) );
                }              
            }            
            
            buildBlogAttributes(blogs);
            Collections.sort(blogs, new BlogComparator());
            
            response.setResponse(blogs);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);    
        }
        return response; 
    }

    @Override
    public ServiceResponse<Boolean> update(Blog blog) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            String targetID = blog.getId(); 
            Blog targetBlog = blogDao.getById(targetID);
            
            //CX: update dabase record
            if (targetBlog != null) {                 
                targetBlog.setBlogTypeID(blog.getBlogTypeID());

                targetBlog.setTitle(blog.getTitle());
                targetBlog.setBody(blog.getBody());
                targetBlog.setShortBody(blog.getShortBody());

                targetBlog.setAuthorName(blog.getAuthorName());
                targetBlog.setAuthorGPlus(blog.getAuthorGPlus());
                targetBlog.setTagIDs(blog.getTagIDs());
                targetBlog.setPlaceIDs(blog.getPlaceIDs());

                targetBlog.setDateModified(new Date());  
                
                blogDao.update(targetBlog);
                success = true;
            }  
                
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);  
        }
        return response;
    }

    @Override
    public ServiceResponse<Boolean> delete(String id) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            blogDao.deleteById(id);
            success = true;
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<List<Blog>> readAllByType(int offset, int limit, String blogTypeID) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
        
    private void buildBlogAttributes(List<Blog> blogs) {
        if (blogs != null && blogs.size() > 0) {
            for (Blog blog : blogs) {
                buildBlogAttribute(blog);                
            }
        }
    }
    
    private void buildBlogAttribute(Blog blog) {
        if (!StringUtils.isEmpty(blog.getTitle())) {
            blog.setUrlTitle( blog.getTitle().trim().toLowerCase().replaceAll(",", "").replaceAll(" ", "-") );                    
        }

        //CX: populate photoIDs
        blog.setPhotoIDs(photoDao.getBlogPhotoIds(blog.getId()));

        //CX: populate photos
        blog.getPhotos().clear();                
        if (blog.getPhotoIDs() != null && blog.getPhotoIDs().size() > 0) {
            ServiceResponse<Photo> sr2 = null;

            for (String photoID : blog.getPhotoIDs()) {
                sr2 = this.photoService.read(photoID);                        
                if (sr2.isSuccessful() && sr2.getResponse() != null) {
                    blog.getPhotos().add(sr2.getResponse());
                }
            }                    
        }

        //CX: populate primary            
        if (blog.getPhotos() != null && blog.getPhotos().size() > 0) {
            blog.setPrimaryPhoto(blog.getPhotos().get(0));
        }
    }
    
}
